<?php
/**
 * Created by PhpStorm.
 * User: lx
 * Date: 2020/1/3
 * Time: 9:37
 */
namespace app\api\controller;

use app\api\model\MtUser;
use app\util\ReturnCode;
use think\cache\driver\Redis;
use think\facade\App;
use \think\Request;
use app\command\controller\Testing;
use app\model\mt_user;
use app\command\controller\Generate;
use app\command\controller\MyCurl;
use think\Validate;

/**
 * Class User
 * @package app\api\controller
 * 小程序用户主类
 */
class UserLogin extends Base
{
    public function __construct(){
        parent::__construct();
    }

    /**
     * 获取用户openid
     * 通过wx接口拿code换取用户openid
     * @todo
     * @return int|string|void
     */
    public function userLogin(){
        $js_code = $this->request->get("js_code");
        if(!$js_code){
            return $this->error(ReturnCode::EMPTY_PARAMS,"js_code缺失");
        }
        $openidRequestArr = $this->getUserOpenID($js_code); // 换取用户openID
        if($openidRequestArr['errcode'] !== 0 || !$openidRequestArr['openid']){
            return $this->error(ReturnCode::EMPTY_PARAMS,"openID获取失败",$openidRequestArr);
        }
        $obj = new MtUser();
        $userCount = $obj->where([["openID","=",$openidRequestArr['openid']],["status","=","1"]])->count();
        $timeStap = $userCount ? "mTime" : "cTime";
        $userData = [
            "openID" => $openidRequestArr['openid'],
            $timeStap  => time(),
            "lastLoginTime" => time(),
            "lastLoginIP" => ip2long($this->request->ip()),
        ];
        $res = $obj->save($userData); // 更新表
        if(!$res){
            return $this->error(ReturnCode::DB_SAVE_ERROR,"用户信息更新失败");
        }
        $userToken = $this->userToken($openidRequestArr['openid']); // 兑换token
        (new Redis())->set($openidRequestArr['openid'],$openidRequestArr['session_key']); // 存储sessionkey
        return $this->success("登录成功",['token'=>$userToken]);
    }

    /**
     * 获取用户openid
     * @param $js_code
     * @return mixed
     */
    public function getUserOpenID($js_code){
        $appID = config("apiadmin.APPID");
        $appSecret = config("apiadmin.APPSECRET");
        $url = $this->openIDUrl."?appid=".$appID."&secret=".$appSecret."&js_code=".$js_code."&grant_type=authorization_code";
        $openidRequestJson = (new MyCurl())->curlRequest($url);
        $openidRequestArr = json_decode($openidRequestJson,true);
        return $openidRequestArr;
    }
    /**
     * 存储用户信息
     * @return mixed
     */
//    public function saveUserInfo($openArr = []){
//        if(!$openArr || !is_array($openArr) || !$openArr['openid']){
//            return $this->error(ReturnCode::TYPE_ERROR,"参数错误",$openArr);
//        }
//
//        $obj = new mt_user();
//        $res = $obj->insert([
//            "openID" => $openID,
//            "headerImg" => $headerImg,
//            "nickName" => $nickName,
//            "cTime" => date("YmdHis"),
//            "inviteCode" => (new Generate)->produceInviteCode($openID),
//        ],true);
//        if ($res === 2) {
//            return $this->error(ReturnCode::ADD_REPEAT, "openid重复数据");
//        } elseif ($res === 1) {
//            $this->userID = $obj->getLastInsID();
//            return $this->success("添加成功");
//        }
//        return $this->error(ReturnCode::ADD_FAILED, "添加失败");
//    }
}